<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="filters">
                <el-form-item>
                    <el-input v-model="filters.keyword" placeholder="关键字"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="search">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="success" @click="handleAdd">新增</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="danger" @click="onsale" :disabled="this.sels.length===0">上架</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="warning" @click="offsale" :disabled="this.sels.length===0">下架</el-button>
                </el-form-item>
            </el-form>
        </el-col>

        <el-table :data="products" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column type="index" width="60">
            </el-table-column>
            <el-table-column prop="name" label="名称" width="260" sortable>
            </el-table-column>
            <el-table-column prop="saleprice" label="售价" width="130" sortable>
            </el-table-column>
            <el-table-column prop="costprice" label="成本" width="100" sortable>
            </el-table-column>
            <el-table-column prop="onsaletime" label="上架时间" width="160" sortable>
            </el-table-column>
            <el-table-column prop="offsaletime" label="下架时间" width="160" sortable>
            </el-table-column>
            <!--:formatter="formatState"-->
            <el-table-column prop="state" label="状态" width="120"  sortable>
                <template scope="scope">
                    <span style="color: green" v-if="scope.row.state==0">下架</span>
                    <span style="color: red" v-else-if="scope.row.state==1">上架</span>
                    <span style="color: darkblue" v-else>未知</span>
                </template>
            </el-table-column>
            <!--关联查询-后台查询出来后，前台只需要通过关系属性.要显示的字段名就ol-->
            <el-table-column prop="salecount" label="销量" width="80" sortable>
            </el-table-column>
            <el-table-column label="操作">
                <template scope="scope">
                    <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--工具条-->
        <el-col :span="24" class="toolbar">
            <!--如果没有选中就不能使用:disabled="this.sels.length===0"-->
            <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
            <el-pagination layout="prev, pager, next" :current-page="page" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="float:right;">
            </el-pagination>
        </el-col>

        <!--新增或编辑界面-->
        <el-dialog :title="title" :visible.sync="productFormVisible" :close-on-click-modal="false">
            <!--:model="productForm 模型绑定-->
            <!--:rules="productFormRules" 校验规则-->
            <!--ref="productForm" 给该表单定义一个引用名-->
            <el-form :model="productForm" label-width="80px" :rules="productFormRules" ref="productForm">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="productForm.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="售价" prop="saleprice">
                    <el-input v-model="productForm.saleprice" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="成本" prop="costprice">
                    <el-input v-model="productForm.costprice" auto-complete="off"></el-input>
                </el-form-item>

                <el-form-item label="缩略图" prop="resources">
                    <!--<el-input v-model="productForm.resources" auto-complete="off"></el-input>-->
                    <el-upload
                            class="upload-demo"
                            action="http://localhost:8080/fastDfs"
                            :on-preview="handlePreview"
                            :on-remove="handleRemove"
                            :on-success="handleSuccess"
                            :file-list="fileList"
                            list-type="picture">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                    </el-upload>

                </el-form-item>

                <el-form-item label="简介" prop="intro">
                    <!--<el-input v-model="productForm.detail.intro" auto-complete="off"></el-input>-->
                    <quill-editor v-model="productForm.detail.intro"
                                  :options="quillOption">
                    </quill-editor>
                </el-form-item>
                <el-form-item label="预约须知" prop="orderNotice">
                    <!--<el-input v-model="productForm.detail.orderNotice" auto-complete="off"></el-input>-->
                    <quill-editor v-model="productForm.detail.orderNotice"
                                  :options="quillOption">
                    </quill-editor>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="productFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="save" :loading="productLoading">提交</el-button>
            </div>
        </el-dialog>

    </section>
</template>

<script>
    //引入  vue-quill-editor
    import { quillEditor } from "vue-quill-editor"; //调用编辑器
    import 'quill/dist/quill.core.css';
    import 'quill/dist/quill.snow.css';
    import 'quill/dist/quill.bubble.css';
    import quilConfig from "../../common/js/quill-config"

    export default {
        components: {
            quillEditor
        },
        data() {
            return {
                quillOption:quilConfig,
                filters: {
                    keyword: ''
                },
                products: [],
                fileList:[],
                total: 0,
                page: 1,
                pageSize:10,
                listLoading: false,
                sels: [],//列表选中列

                productFormVisible: false,//新增界面是否显示
                productLoading: false,
                productFormRules: {
                    name: [
                        { required: true, message: '请输入名称', trigger: 'blur' }
                    ]
                },
                title:"",
                productForm: {
                    id:null,
                    name: '',
                    resources: '',
                    saleprice: 0,
                    costprice: 0,
                    detail:{
                        id:null,
                        intro:"",
                        orderNotice:""
                    }
                },
            }
        },
        methods: {
            onsale(){
                var ids = this.sels.map(item => item.id);//[1,2,3]
                //获取选中的行
                if(!this.sels || this.sels.length  <1){
                    this.$message({ message: '老铁，你不选中数据，臣妾上架不了啊....',type: 'error'});
                    return;
                }
                this.$confirm('确认上架选中记录吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    this.$http.post('/product/onsale',ids).then((res) => {
                        this.listLoading = false;

                        if(res.data.success){
                            this.$message({
                                message: '上架成功',
                                type: 'success'
                            });
                        }else{
                            this.$message({
                                message: res.data.message,
                                type: 'error'
                            });
                        }
                        this.getProducts();
                    });
                }).catch(() => {

                });
            },
            offsale(){

                var ids = this.sels.map(item => item.id);
                //获取选中的行
                if(!this.sels || this.sels.length  <1){
                    this.$message({ message: '老铁，你不选中数据，臣妾下架不了啊....',type: 'error'});
                    return;
                }
                this.$confirm('确认下架选中记录吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    this.$http.post('/product/offsale',ids).then((res) => {
                        this.listLoading = false;

                        if(res.data.success){
                            this.$message({
                                message: '下架成功',
                                type: 'success'
                            });
                        }else{
                            this.$message({
                                message: res.data.message,
                                type: 'error'
                            });
                        }
                        this.getProducts();
                    });
                }).catch(() => {

                });
            },
            handleSuccess(response, file, fileList){
                console.log(fileList);
                let resourceTemp = "";
                for(let i=0;i<fileList.length;i++){
                    //如果是数组的最后一个元素，不要加逗号了
                    if(i == fileList.length -1){
                        resourceTemp = resourceTemp + fileList[i].response.resultObj;
                    }else{//如果不是最后一个 拼接上逗号
                        resourceTemp = resourceTemp + fileList[i].response.resultObj + ",";
                    }
                }
                this.productForm.resources = resourceTemp;
            },
            handleRemove(file, fileList) {
                var filePath =file.response.resultObj;
                this.$http.delete("/fastDfs/?path="+filePath)
                    .then(res=>{
                        if(res.data.success){
                            this.$message({
                                message: '删除成功!',
                                type: 'success'
                            });
                            let resourceTemp = "";
                            for(let i=0;i<fileList.length;i++){
                                //如果是数组的最后一个元素，不要加逗号了
                                if(i == fileList.length -1){
                                    resourceTemp = resourceTemp + fileList[i].response.resultObj;
                                }else{//如果不是最后一个 拼接上逗号
                                    resourceTemp = resourceTemp + fileList[i].response.resultObj + ",";
                                }
                            }
                            this.productForm.resources = resourceTemp;
                        }else{
                            this.$message({
                                message: '删除失败!',
                                type: 'error'
                            });
                        }
                    })
            },
            handlePreview(file) {
                console.log(file);
            },
            search() {
                //查询完，原来分页条件已经没用了，要跑到第一页去
                this.page = 1;
                this.getProducts();
            }
            ,
            handleCurrentChange(val) {
                this.page = val;
                this.getProducts();
            },
            //获取服务列表
            getProducts() {
                let para = {
                    currentPage: this.page,
                    pageSize:this.pageSize,
                    keyword: this.filters.keyword
                };
                this.listLoading = true;
                this.$http.post("/product",para)
                    .then(result=>{
                        result = result.data; //取出data这一层
                        this.total = result.totalCount;
                        this.products = result.data;
                        this.listLoading = false;
                    })
                    .catch(result=>{
                        this.$message({
                            message: '系统错误',
                            type: 'error'
                        });
                    })
            },
            //显示编辑界面
            handleEdit: function (index, row) {
                this.fileList = [];
                this.title = "编辑";
                row.detail={};//复制的时候，有空属性会报错，这里要提前设置
                this.productForm = Object.assign({}, row); //回显
                this.$http.get("/product/detail/"+row.id)
                    .then(result=>{
                        this.productForm.detail=result.data;

                    })
                    .catch(result=>{
                        this.$message({
                            message: '系统错误',
                            type: 'error'
                        });
                    });
                let resourcesTmp = row.resources;//  /group1/M00/00/83/rBEAA2Bq0BSAbF1uAADyXoRe0ps940.jpg,/group1/M00/00/83/rBEAA2Bq0BqAT5kPAADy2SHkIGA358.jpg
                resourcesTmp = resourcesTmp.split(",");//[/group1/M00/00/83/rBEAA2Bq0BSAbF1uAADyXoRe0ps940.jpg,/group1/M00/00/83/rBEAA2Bq0BqAT5kPAADy2SHkIGA358.jpg]

                for(let i=0;i<resourcesTmp.length;i++){
                    //因为在操作图片的时候，需要重新从fileList中取值赋值给表单
                    //fileList[i].response.resultObj;
                    this.fileList.push(
                        {"url":"http://115.159.217.249:8888/"+resourcesTmp[i],
                            "response":
                                {"resultObj":resourcesTmp[i]}
                        });
                }
                this.productFormVisible = true; // 显示编辑框


            },
            //显示新增界面
            handleAdd: function () {
                this.fileList = [];
                this.title = "新增";
                this.productForm = { //清空
                    id:null,
                    name: '',
                    resources: '',
                    saleprice: 0,
                    costprice: 0,
                    detail:{
                        id:null,
                        intro:"",
                        orderNotice:""
                    }
                }

                this.productFormVisible = true; //显示新增框
            },
            //保存
            save: function () {
                // 表单上定义了ref="productForm"
                this.$refs.productForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认保存吗？', '温馨提示', {}).then(() => {
                            this.productLoading = true;
                            //拷贝一份新数据
                            let para = Object.assign({}, this.productForm);
                            this.$http.put("/product",para)
                                .then(result => {
                                    result = result.data
                                    //去除忙等框
                                    this.productLoading = false;
                                    //做提示
                                    if(result.success){
                                        this.$message({
                                            message: '保存成功',
                                            type: 'success'
                                        });
                                    }else{
                                        this.$message({
                                            message: result.message,
                                            type: 'error'
                                        });
                                    }
                                    //关闭对话框
                                    this.productFormVisible =false;
                                    //重新查询数据
                                    this.getProducts();
                                })
                                .catch(result=>{
                                    alert("系统错误！");
                                    this.productLoading = false;
                                })
                            ;
                        });
                    }
                });
            },
            //所有选中对象都会传进来
            selsChange: function (sels) {
                this.sels = sels;
                console.log(this.sels)
            },
            //删除
            handleDel: function (index, row) {
                this.$confirm('确认删除该记录吗?', '温馨提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    let url = "/product/"+row.id;
                    this.$http.delete(url)
                        .then(result=>{
                                result = result.data; //{sucess:false,message}
                                //去除忙等框
                                this.listLoading = false;

                                if(result.success){
                                    this.page = 1;
                                    //提示
                                    this.$message({
                                        message: '删除成功',
                                        type: 'success'
                                    });
                                    //重新查询数据
                                    this.getProducts();
                                }else{
                                    //提示
                                    this.$message({
                                        message: result.message,
                                        type: 'error'
                                    });
                                    //重新查询数据
                                    this.getProducts();
                                }
                            }

                        )
                        .catch(result=>{
                            //去除忙等框
                            this.listLoading = false;
                            //提示
                            this.$message({
                                message: '系统错误！',
                                type: 'error'
                            });
                        })

                }).catch(() => {

                });
            },
            //批量删除
            batchRemove: function () {
                var ids = this.sels.map(item => item.id); //[1,2,3]
                console.log(ids);
                this.$confirm('确认删除选中记录吗？', '温馨提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    //传递数组参数
                    this.$http.patch("/product",ids)
                        .then(result=>{
                            result = result.data;
                            this.listLoading = false;
                            if(result.success){
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                            }else{
                                this.$message({
                                    message: result.message,
                                    type: 'error'
                                });
                            }
                            this.page =1; //删除后跳转第一页
                            this.getProducts();
                        })
                        .catch(result=>{
                            alert("系统错误")
                        })
                }).catch(() => {

                });
            }

        },
        mounted() {
            this.getProducts();
        }
    }

</script>

<style scoped>

</style>